package com.bfmet.common.base;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;

import com.bfmet.common.BfmetException;

public abstract class UtilBase {

	static {
		System.getProperties().put("http.proxyHost", "www-proxy.us.oracle.com");
		System.getProperties().put("http.proxyPort", "80");
	}

	protected Logger logger = Logger.getLogger(getClass().getName());

	protected final Lock lock = new ReentrantLock();

	public UtilBase() {
		logger.setLevel(Level.INFO);
	}

	protected void log(String message) {
		logger.info(message);
	}

	public void logException(Throwable throwable) {
		logBfmetException(throwable, "");
	}

	public void logBfmetException(Throwable throwable, String message) {
		BfmetException ae = new BfmetException(message, throwable);
		logger.log(Level.SEVERE, ae.getMessage(),ae);
	}

	protected String removeHtmlTags(String input) {
		if (input == null || input.trim().equals("")) {
			return "";
		}
		// remove all html tags,
		String str = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll(
				"<[^>]*>", "");
		str = str.replaceAll("[(/>)<]", "");
		return str;
	}

	protected String filterHtmlTags(String input, int length) {
		String str = this.removeHtmlTags(input);
		int len = str.length();
		if (len <= length) {
			return str;
		} else {
			str = str.substring(0, length);
			str += "......";
		}
		return str;
	}

	protected String getSuffix(String inputString) {
		String suffix = inputString;
		if (inputString.indexOf(".") != -1) {
			suffix = inputString.substring(inputString.lastIndexOf(".") + 1,
					inputString.length());
		}
		this.log(suffix);
		return suffix;
	}

	protected int getIntValue(String input) {
		int value = 0;
		try {
			if (this.isNumeric(input)) {
				value = Integer.valueOf(input).intValue();
			}
		} catch (Exception ex) {
			this.logBfmetException(ex, "convert error:" + input);
		}
		return value;
	}

	public boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}
}
